package com.haifeng.sbtx.auth.exception;

import com.haifeng.sbtx.common.base.ErrorCode;
import com.haifeng.sbtx.common.constant.Constants;
import com.haifeng.sbtx.common.util.MessageUtil;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  自定义异常转换器
 * </p>
 *
 * @author: Haifeng
 * @date: 2019-12-15
 */
@Component
@AllArgsConstructor
public class CustomWebResponseExceptionTranslator implements WebResponseExceptionTranslator {

    private final MessageUtil messageUtil;

    @Override
    public ResponseEntity translate(Exception e) throws Exception {
        OAuth2Exception exception = (OAuth2Exception) e;
        Map map = new HashMap(16);
        map.put("data",null);
        map.put("code",401);
        map.put("success",false);
        String message = exception.getMessage();
        if (message.contains(Constants.INVALID_REFRESH_TOKEN)){
            message = messageUtil.getMessage(ErrorCode.INVALID_REFRESH_TOKEN);
        }else if (message.contains(Constants.INVALID_AUTHORIZATION_CODE)){
            message = messageUtil.getMessage(ErrorCode.INVALID_AUTHORIZATION_CODE);
        }else if (message.contains(Constants.BAD_CREDENTIALS)){
            message = messageUtil.getMessage(ErrorCode.BAD_CREDENTIALS);
        }else if (message.contains(Constants.TOKEN_WAS_NOT_RECOGNISED)){
            message = messageUtil.getMessage(ErrorCode.TOKEN_WAS_NOT_RECOGNISED);
        }else if (message.contains(Constants.INVALID_SCOPE)){
            message = messageUtil.getMessage(ErrorCode.INVALID_SCOPE);
        }else if (message.contains(Constants.UNSUPPORTED_GRANT_TYPE)){
            message = messageUtil.getMessage(ErrorCode.UNSUPPORTED_GRANT_TYPE);
        }else if (message.contains(Constants.MISSING_GRANT_TYPE)){
            message = messageUtil.getMessage(ErrorCode.MISSING_GRANT_TYPE);
        }else if (message.contains(Constants.AN_AUTHORIZATION_CODE_MUST_BE_SUPPLIED)){
            message = messageUtil.getMessage(ErrorCode.AN_AUTHORIZATION_CODE_MUST_BE_SUPPLIED);
        }
        map.put("message",message);
        if (exception.getAdditionalInformation()!=null) {
            for (Map.Entry<String, String> entry : exception.getAdditionalInformation().entrySet()) {
                String key = entry.getKey();
                String add = entry.getValue();
                map.put(key,add);
            }
        }
        return ResponseEntity.ok(map);
    }
}

